package com.sy.sevice.impl;

import com.sy.dto.JsonResult;
import com.sy.entity.ClassEntity;
import com.sy.mapper.ClassMapper;
import com.sy.sevice.ClassService;
import com.sy.utils.CommonUtils;
import com.sy.vo.AddClassVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Monkey-D-Gu
 * @version 1.0
 * @date 2020/9/14 0014 13:40
 * @usage 班级相关的Service层实现类
 */
@Service
public class ClassServiceImpl implements ClassService {

    @Autowired
    private ClassMapper classMapper;
    /**
     * 新增班级信息
     * @return JsonResult对象
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public JsonResult addNewClass(ClassEntity classEntity) {
        String name = classEntity.getName();
        //获取所有的班级名称集合
        List<String> classNameList = classMapper.getAllClassNames();
        if (null != classNameList) {
            if (classNameList.contains(name)) {
                return JsonResult.buildFailure(400,"班级名称已存在");
            }
        }
        //新增班级表信息
        boolean addSuccess = classMapper.addClass(classEntity);
        System.out.println("是否添加成功：" + addSuccess);
        //返回的自增主键
        Integer id = classEntity.getId();
        //需要生成的表名
        String tableName = CommonUtils.getTableName(id);
        //生成新的表
        classMapper.createNewTable(tableName);
        return null;
    }
}
